<template>
    <div class="app-container">
        <el-row class="wrapper domain">
            <el-col :span="24" class="warp-main">
                <div class="el-bar">
                    <!--工具条-->
                    <el-col :span="24" class="toolbar" style="padding-top:10px">
                        <el-form :inline="true">
                            <el-form-item>
                                <el-button @click="addDomainDialogOpen" icon="el-icon-plus" type="primary">创建域名访问</el-button>
                            </el-form-item>
                            <el-form-item>
                                <el-input style="width:250px" v-model="queryKey" placeholder="域名/域名访问名称/映射的服务名">
                                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                                </el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button @click="ingressQuery" icon="el-icon-search" type="primary">查询</el-button> 共{{ingressData.length}}条记录
                            </el-form-item>
                        </el-form>
                    </el-col>

                    <!--数据列表-->
                    <el-table v-loading="loadingDataTable" :data="ingressData" highlight-current-row style="width: 100%;">
                        <!-- <el-table-column :show-overflow-tooltip="true" width="110" prop="name" label="域名访问名称" sortable></el-table-column> -->
                        <el-table-column width="350" prop="ingressRules" label="域名映射规则" sortable>
                            <template slot-scope="scope">
                                <div v-html="format(scope.row.ingressRules)">{{ format(scope.row.ingressRules) }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column width="270" prop="ingressDesc" label="描述" sortable></el-table-column>
                        <el-table-column prop="creationTimestamp" label="已创建" sortable></el-table-column>
                        <el-table-column label="操作" fixed="right" width="300">
                            <template slot-scope="scope">
                                <el-button @click="deleteIngress(scope.$index, scope.row)" icon="el-icon-delete" type="danger" size="mini">删除</el-button>
                                <el-button @click="updateDomainDialogOpen(scope.$index, scope.row)" icon="el-icon-edit" type="primary" size="mini">修改/查看</el-button>
                                <el-dropdown split-button size="mini" type="primary">
                                    访问
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item v-for="(access, index) in getRules(scope.row)" :key="access.key" :prop="'access.' + index + '.value'">
                                            <a target="_blank" :href="'http://' + access " class="help-center">{{access}}</a>
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!--新增/修改域名访问信息-->
                    <el-dialog ref="dialog" :title="domainTitle" :visible.sync="domainVisible" :close-on-click-modal="true" width="850px">
                        <el-form :inline="true" :rules="rules1" ref="f1" :model="form" class="form-top">
                            <!-- <el-form-item label="名称" prop="name">
                                    <el-input :disabled="domainNameDisabled" v-model="form.name" style="width:200px" placeholder="域名访问名称"></el-input>
                                </el-form-item> -->
                            <el-form-item label="描述" prop="ingressDesc">
                                <el-input v-model="form.ingressDesc" style="width:300px" placeholder="域名访问描述"></el-input>
                            </el-form-item>
                        </el-form>
                        <el-form :inline="true" ref="f2" :model="form">
                            <el-form-item label="映射的服务域名" label-width="150px" />
                            <el-form-item style="margin-left:125px" label="映射的服务选择" label-width="150px" />
                            <el-form-item style="margin-left:70px" label="服务端口" label-width="70px" />
                            <el-form-item style="margin-left:30px" label="映射的服务访问路径" label-width="150px" />
                        </el-form>
                        <el-form :inline="true" ref="f3" :rules="rules1" :model="form" class="form-top" v-for="(ingressRule, index) in form.ingressRules" :key="ingressRule.key">
                            <el-form-item style="margin-left:45px" label="" :prop="'ingressRules.' + index + '.value'">
                                <el-input style="width:180px;" v-model="ingressRule.host"></el-input>
                                <el-tooltip class="item" effect="dark" content="删除映射的服务域名">
                                    <el-button type="danger" @click.prevent="removeDomain1(ingressRule)">-</el-button>
                                </el-tooltip>
                                <el-tooltip class="item" effect="dark" content="增加映射的服务路径">
                                    <el-button type="primary" @click="addDomain2(ingressRule)">+</el-button>
                                </el-tooltip>
                            </el-form-item>
                            <el-form-item label="">
                                <el-form :inline="true" ref="f4" :model="form" class="form-top" v-for="(ingressHttpPath, index) in ingressRule.ingressHttpPaths" :key="ingressHttpPath.key" :prop="'ingressHttpPaths.' + index + '.value'">
                                    <el-form-item label="">
                                        <el-select style="width:180px;margin-left:10px" v-model="ingressHttpPath.backend.serviceName" placeholder="服务名">
                                            <el-option v-for="item in serviceData" :key="item.name" :label="item.name" :value="item.name">
                                            </el-option>
                                        </el-select>
                                        <el-select style="width:90px;" v-model="ingressHttpPath.backend.servicePort" placeholder="端口">
                                            <el-option v-for="item1 in getServicePorts(ingressHttpPath.backend.serviceName)" :key="item1.port" :label="item1.port" :value="item1.port">
                                            </el-option>
                                        </el-select>
                                        <el-input style="width:100px;margin-left:20px" v-model="ingressHttpPath.path"></el-input>
                                        <el-tooltip class="item" effect="dark" content="删除服务选择">
                                            <el-button type="danger" @click.prevent="removeDomain2(ingressRule,ingressHttpPath)">-</el-button>
                                        </el-tooltip>
                                    </el-form-item>
                                </el-form>
                            </el-form-item>
                        </el-form>
                        <div style="margin-left:45px">
                            <el-tooltip class="item" effect="dark" content="增加映射的服务域名">
                                <el-button type="primary" @click="addDomain1">+</el-button>
                            </el-tooltip>
                        </div>
                        <div slot="footer" class="dialog-footer">
                            <el-button class="iconfont icon-chehui" @click="domainVisible=false">取消</el-button>
                            <el-button class="iconfont icon-fuxuan" @click="addOrUpdateServiceSubmit" type="primary">确定</el-button>
                        </div>
                    </el-dialog>
                </div>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import { Notification } from 'element-ui';
export default {
    data() {
        var validateIngressDesc = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('描述不能为空!'));
            } else {
                callback();
            }
        };
        return {
            //查询关键词
            queryKey: '',
            //节点数据
            ingressData: [
            ],
            // 任务查询遮罩
            loadingDataTable: true,
            domainNameDisabled: true,
            serviceData: [
            ],

            domainTitle: '域名访问新增',//新增或者修改域名访问标题
            domainVisible: false,      //新增或者修改是否显示

            form: {//domain 的 form
                name: '',
                namespace: '',
                ingressClass: '',
                ingressDesc: '',
                creationTimestamp: '',
                ingressRules: [
                    {
                        host: '',
                        ingressHttpPaths: [
                            {
                                backend: {
                                    serviceName: '',
                                    servicePort: 0
                                },
                                path: '/'
                            }
                        ]
                    }

                ],
            },
            rules1: {
                ingressDesc: [
                    { validator: validateIngressDesc, trigger: 'blur' }
                ]
            }

        }
    },
    methods: {
        S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        },
        guid() {
            return (this.S4() + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + this.S4() + this.S4());
        },

        removeDomain1(item) {
            if (this.form.ingressRules.length == 1) {
                this.$message({
                    message: '至少需要创建1个服务域名!',
                    type: 'warning'
                });
                return;
            }
            var index = this.form.ingressRules.indexOf(item)
            if (index != -1) {
                this.form.ingressRules.splice(index, 1)
            }
        },
        removeDomain2(ingressRule, ingressHttpPath) {
            if (ingressRule.ingressHttpPaths.length == 1) {
                this.$message({
                    message: '每个服务域名至少需要添加1个映射的服务!',
                    type: 'warning'
                });
                return;
            }
            var index = ingressRule.ingressHttpPaths.indexOf(ingressHttpPath)
            if (index != -1) {
                ingressRule.ingressHttpPaths.splice(index, 1)
            }
        },
        addDomain1() {
            this.form.ingressRules.push({
                host: '',
                ingressHttpPaths: [
                    {
                        backend: {
                            serviceName: '',
                            servicePort: 0
                        },
                        path: '/'
                    }
                ]
            });
        },
        addDomain2(ingressRule) {
            ingressRule.ingressHttpPaths.push({
                backend: {
                    serviceName: '',
                    servicePort: 0
                },
                path: '/'
            });
        },

        getServicePorts(serviceNames) {
            if (serviceNames == '') {
                return [];
            }
            let rArr = [];
            this.serviceData.forEach(function(ele) {
                if (ele.name == serviceNames) {
                    rArr = ele.servicePorts;
                    return;
                }
            });
            return rArr;
        },

        //新增域名访问窗口开启
        addDomainDialogOpen() {
            let currentNs = this.userBaseInfo.getCurrentSelectedNamespace();
            this.domainTitle = "新增域名访问";
            this.form = {//domain 的 form
                name: this.guid(),
                namespace: currentNs,
                ingressClass: '',
                ingressDesc: '',
                creationTimestamp: '',
                ingressRules: [
                    {
                        host: '',
                        ingressHttpPaths: [
                            {
                                backend: {
                                    serviceName: '',
                                    servicePort: 0
                                },
                                path: '/'
                            }
                        ]
                    }

                ],
            }
            this.domainVisible = true;
            if (this.$refs['f1'] != undefined) {
                this.$refs['f1'].resetFields();
            }
        },

        //修改域名访问窗口开启
        updateDomainDialogOpen(index, row) {
            let currentNs = this.userBaseInfo.getCurrentSelectedNamespace();
            this.domainTitle = "修改域名访问";
            this.form = row;
            this.domainVisible = true;
            if (this.$refs['f1'] != undefined) {
                this.$refs['f1'].resetFields();
            }
        },

        //新增/修改服务创建提交
        addOrUpdateServiceSubmit() {
            this.$refs['f1'].validate((valid) => {
                if (valid) {
                    //校验服务域名
                    let errorFlag = false;
                    this.form.ingressRules.forEach(ele => {
                        if (ele.host == '') {
                            this.$message({
                                message: '映射的服务域名不能为空!',
                                type: 'warning'
                            });
                            errorFlag = true;
                            return;
                        } else {
                            ele.ingressHttpPaths.forEach(ele1 => {
                                if (ele1.backend.serviceName == '') {
                                    this.$message({
                                        message: '服务选择不能为空!',
                                        type: 'warning'
                                    });
                                    errorFlag = true;
                                    return;
                                };
                                if (ele1.backend.servicePort == '' || ele1.backend.servicePort == 0) {
                                    this.$message({
                                        message: '服务端口不能为空!',
                                        type: 'warning'
                                    });
                                    errorFlag = true;
                                    return;
                                }
                                if (ele1.path == '') {
                                    this.$message({
                                        message: '映射的服务访问路径不能为空!',
                                        type: 'warning'
                                    });
                                    errorFlag = true;
                                    return;
                                }
                                var pattern = /^\/.*/;
                                if (!pattern.test(ele1.path)) {
                                    this.$message({
                                        message: '映射的服务访问路径必须以/开始!',
                                        type: 'warning'
                                    });
                                    errorFlag = true;
                                    return;
                                }
                            });
                        }
                    });
                    if (!errorFlag) {
                        // 遮罩开始
                        const loading = this.$loading({ body: true });
                        if(this.domainTitle == "新增域名访问"){
                            this.userBaseInfo.setOperObjectName("新增域名访问:"+this.form.ingressDesc);
                        }else{
                            this.userBaseInfo.setOperObjectName("修改域名访问:"+this.form.ingressDesc);
                        }
                        
                        this.httpClient.httpClientPost(this.projectConfig.URL_API_APP_MANAGE_APP_INGRESS, this.form).then(res => {
                            // 遮罩结束
                            loading.close();
                            let r = res.data;
                            if (r) {
                                this.domainVisible = false;
                                this.ingressQuery();
                            } else {
                                this.$message({
                                    message: '新增/修改服务失败!',
                                    type: 'warning'
                                });
                            }
                        })
                    }
                } else {
                    return false;
                }
            });
        },

        //服务查询
        serviceQuery() {
            let currentNs = this.userBaseInfo.getCurrentSelectedNamespace();
            let url = this.projectConfig.URL_API_APP_MANAGE_APP_SERVICE_LIST_BY_NAMESPACE;
            url += "?namespace=" + currentNs + "&queryKey=";
            this.httpClient.httpClientget(url).then((response) => {
                let data = response.data;
                this.serviceData = data;
            }).catch(error => {
            });
        },

        //查询
        ingressQuery() {
            let currentNs = this.userBaseInfo.getCurrentSelectedNamespace();
            let url = this.projectConfig.URL_API_APP_MANAGE_APP_INGRESS_LIST;
            url += "?namespace=" + currentNs + "&queryKey=" + this.queryKey;
            // 开启遮罩
            this.loadingDataTable = true;
            this.httpClient.httpClientget(url).then((response) => {
                // 遮罩结束
                this.loadingDataTable = false;
                let data = response.data;
                this.ingressData = data;
            }).catch(error => {
                // 遮罩结束
                this.loadingDataTable = false;
            });
        },

        format(cellValue) {
            let str = "";
            cellValue.forEach(function(element) {
                if (str != "") {
                    str += "<br>";
                }
                let host = element.host;
                let ingressHttpPaths = element.ingressHttpPaths;
                let i = 0;
                ingressHttpPaths.forEach(function(element1) {
                    if (i > 0) {
                        str += "<br>";
                    }
                    str += host;
                    str += element1.path;
                    str += " -> ";
                    str += element1.backend.serviceName + ":" + element1.backend.servicePort;
                    i++;
                }, this);
            }, this);
            return str;
        },

        getRules(row) {
            let rules = [];
            row.ingressRules.forEach(function(element) {
                let host = element.host;
                let ingressHttpPaths = element.ingressHttpPaths;
                ingressHttpPaths.forEach(function(element1) {
                    rules.push(host + element1.path);
                }, this);
            }, this);
            return rules;
        },

        // 删除域名
        deleteIngress: function(index, row) {
            this.$confirm("此操作将永久删除此域名访问, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    let url = this.projectConfig.URL_API_APP_MANAGE_APP_INGRESS;
                    url += "?namespace=" + row.namespace + "&ingressName=" + row.name;
                    this.userBaseInfo.setOperObjectName(row.ingressDesc);
                    this.httpClient.httpClientDelete(url).then((response) => {
                        this.ingressQuery();
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消操作"
                    });
                });
        },
    },
    mounted: function() {
        this.ingressQuery();
        this.serviceQuery()
    },
    computed: {
        getCurrentNamespace() {
            return this.$store.getters.namespace;
        }
    },
    watch: {
        getCurrentNamespace(val) {
            this.ingressQuery();
            this.serviceQuery();
        },

    }
}
</script>

<style>
.domain .el-table tr {
    text-align: center;
}

.domain .el-time {
    border: 1px solid;
    border-radius: 4px;
}

.domain .el-width {
    width: 400px;
}

.domain .el-bar {
    padding-bottom: 50px;
}

.domain .el-bar .nbd {
    border-bottom: none;
}

.domain .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #ccc;
}

.domain el-icon-search {
    border: 1px solid #eaeaea;
    border-radius: 4px;
}

.domain .search .el-input {
    border: 1px solid #eaeaea;
}

.domain .el-date-editor--datetimerange {
    border: 1px solid #eaeaea;
    border-radius: 4px;
}

.domain .el-table .cell {
    padding: 0;
}

.el-dropdown {
    vertical-align: top;
}

.el-dropdown+.el-dropdown {
    margin-left: 15px;
}

.el-icon-arrow-down {
    font-size: 12px;
}
</style>